$(function () {
  const form = layui.form
  const laypage = layui.laypage
  let q = {
    pagenum: 1,
    pagesize: 2,
    cate_id: '',
    state: ''
  }

  template.defaults.imports.dataFormat = function (date) {
    const dt = new Date(date)

    let y = dt.getFullYear()
    let m = padZero(dt.getMonth() + 1)
    let d = padZero(dt.getDate())

    let hh = padZero(dt.getHours())
    let mm = padZero(dt.getMinutes())
    let ss = padZero(dt.getSeconds())
    
    return y + '-' + m + '-' + d + ' ' + hh + ':' + mm + ':' + ss
  }

  // 定义补零的函数
  function padZero(n) {
    return n > 9 ? n : '0' + n
  }
  $.ajax({
    url: '/my/article/cates',
    method: 'GET',
    success: res => {
      if (res.status !== 0) {
        return layer.msg(res.message)
      }

      let htmlTpl = res.data.map(item => {
        return `<option value="${item.Id}">${item.name}</option>`
      }).join('')
      $('[name=cate_id]').html(htmlTpl)

      form.render()
    }
  })


  //调用文章列表接口
  initTable()

  function initTable() {
    $.ajax({
      url: '/my/article/list',
      method: 'GET',
      data: q,
      success: res => {
        if (res.status !== 0) {
          return layer.msg(res.message)
        }

        let htmlTpl = res.data.map(item => {
          return `
          <tr>
            <td>${item.title}</td>
            <td>${item.cate_name}</td>
            <td>${item.pub_date}</td>
            <td>${item.state}</td>
            <td>
              <button type="button" class="layui-btn layui-btn-xs layui-btn-danger del-btn" data-id="${item.Id}">删除</button>
            </td>
          </tr>
          `
        }).join('')

        $('tbody').html(htmlTpl)

        renderPage(res.total)
      }
    })
  }

  //定义分页方法
  function renderPage(total) {
    laypage.render({
      elem: 'page-box',
      count: total,
      curr: q.pagenum,
      limit: q.pagesize,
      limits: [2, 3, 4, 5],
      layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'],
      jump: function (obj, first) {
        q.pagenum = obj.curr
        q.pagesize = obj.limit

        //首次不执行
        if (!first) {
          initTable()
        }
      }
    })
  }

  $('#selectForm').on('submit', e => {
    e.preventDefault()
    let cateId = $('[name=cate_id]').val()
    let state = $('[name=state]').val()

    q.cate_id = cateId
    q.state = state

    initTable()
  })

  $('tbody').on('click', '.del-btn', function () {
    let artId = $(this).attr('data-id')
    layer.confirm('确认删除', { icon: 3, title: '提示' }, index => {
      $.ajax({
        url: '/my/article/delete/' + artId,
        method: 'GET',
        success: res => {
          if (res.status !== 0) {
            return layer.msg(res.message)
          }
          if (length === 1 && q.pagenum > 1) {
            q.pagenum = q.pagenum - 1
          }
          //删除成功判断当前页数是不是只有一条，只有一条数据就需要修改查询参数，先回退一页，再次请求数据
          layer.msg('删除')
          initTable()
        }
      })

      layer.close(index)
    })
  })

})